﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FAS.Objetos;
using Microsoft.Office.Interop.Word;
using System.Windows.Forms;
using System.Drawing;


namespace FAS.App_Code
{
    class Seccion 
    {
        public Seccion(int index, String Materia) 
        {
            this.index = index;
            this.Materia = Materia;
        }

        public int index;
        public String Materia;
    }

    class WordCreator
    {
        Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
        object oMissing = System.Reflection.Missing.Value;
        object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
        private IList<Examen> examenes;
        private Parcial parcial;
        private String nombre;
        private List<Seccion> lstSections = new List<Seccion>();
        public WordCreator(IList<Examen> e, Parcial parcial)
        {
            this.examenes = e;
            this.parcial = parcial;
            this.nombre = examenes.ElementAt(0).pdf + ".pdf";
            Clipboard.Clear();
            createDoc();
        }

        public void createDoc()
        {
            object missing = System.Reflection.Missing.Value;
            object Visible = true;
            object readOnly = false;
            object isVisible = false;
            object start1 = 0;
            object end1 = 0;
            Document adoc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
            //adoc.PageSetup.TogglePortrait();
            Range rng = adoc.Range(ref start1, ref missing);

            try
            {
                hojaRespuestas(adoc);
                object filename = @"C:/Users/Payo/Desktop/lus.docx";
                for (int c = 0; c < examenes.Count;c++ )
                {
                    Examen e = examenes[c];
                    insertText("Clave: " + e.Clave, adoc, 5, 14, 1);
                    int r = 1;
                    foreach (Problema probl in e.Problemas)
                    {
                        insertText("Pregunta " + r + ")", adoc, 8, 15, 0);
                        insertRTF(adoc, probl.Texto);
                        r++;
                        Table newTable;
                        Range wrdRng = adoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                        newTable = adoc.Tables.Add(wrdRng, 2, 4, ref oMissing, ref oMissing);
                        newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                        newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                        newTable.AllowAutoFit = true;
                        int x = 1;
                        String[] opcs = new String[] { "A)", "B)", "C)", "D)" };
                        foreach (String str in opcs)
                        {
                            Cell celda = newTable.Cell(newTable.Rows.Count, x);
                            celda = newTable.Cell(newTable.Rows.Count - 1, x);
                            celda.Range.Text = getText(x);
                            x++;
                        }
                        x = 0;
                        foreach (Opcion cell in probl.Opciones)
                        {
                            ++x;
                            Clipboard.SetText(cell.Texto, TextDataFormat.Rtf);
                            Cell celda = newTable.Cell(newTable.Rows.Count, x);
                            try
                            {
                                pegarTexto(cell.Texto);
                                celda.Range.Paste();
                            }
                            catch (Exception exce)
                            {
                                pegarTexto(cell.Texto);
                                celda.Range.Paste();
                                Console.WriteLine("RANGE EXCEPTION 1");
                            }
                        }
                    }
                    if(c+1 != examenes.Count)
                        newPage(adoc);
                }
                PageNumbersN(adoc);
                adoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                WordApp.Visible = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("" + ex);
                MessageBox.Show("" + ex);
            }
        }

        private void pegarTexto(String texto) 
        {
            Clipboard.SetText(texto, TextDataFormat.Rtf);
        }

        private void PageNumbersN(Document doc)
        {
            int x = 0;
            foreach (Microsoft.Office.Interop.Word.Section section in doc.Sections)
            {
                Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                headerRange.Text = "TEC DE MONTERREY Campus Zacatecas \n Examen de " + parcial.Materia +" \n Periodo " + parcial.Fecha+ " \n "+parcial.ParcialP + " Parcial \n ";
                Microsoft.Office.Interop.Word.HeaderFooter header = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
                Microsoft.Office.Interop.Word.Shape oshape = header.Shapes.AddPicture(@"C:\Users\Payo\Desktop\itesm.png", oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
                x++;
            }
        }

        private void insertProblema(Problema probl, Document adoc)
        {
            Table newTable;
            Range wrdRng = adoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            newTable = adoc.Tables.Add(wrdRng, 1, 1, ref oMissing, ref oMissing);
            newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            newTable.AllowAutoFit = true;
            try
            {
                Clipboard.SetText(probl.Texto, TextDataFormat.Rtf);
                Cell celda = newTable.Cell(newTable.Rows.Count, 1);
                celda.Range.Paste();
            }
            catch (Exception excep)
            {
                Clipboard.SetText(probl.Texto, TextDataFormat.Rtf);
                Cell celda = newTable.Cell(newTable.Rows.Count, 1);
                celda.Range.Paste();
                Console.WriteLine("RANGE EXCEPTION 2");
            }
        }

        private void insertHeaderExamen(Document adoc,Examen e)
        {
            insertTextImage("TEC DE MONTERREY Campus Zacatecas", adoc, 2, 12, 1);
            insertText("Examen de " + parcial.Materia, adoc, 2, 12, 1);
            insertText("Periodo " + parcial.Fecha, adoc, 2, 10, 1);
            insertText(parcial.ParcialP + " Parcial", adoc, 2, 10, 1);
            insertText(e.Clave, adoc, 2, 11, 2);
            insertText("Pagina", adoc, 2, 11, 2);
        }

        private void insertTextImage(String text, Document doc, int bold, int size, int pos)
        {
            Paragraph p = doc.Content.Paragraphs.Add(oMissing);
            Clipboard.SetImage(Image.FromFile("itesm.png"));
            p.Range.Font.Name = "ARIAL";
            p.Range.Font.Bold = bold;
            p.Range.Font.Size = size;
            p.Range.Text = text;
            p.Range.Paste();
            p.Range.ParagraphFormat.Alignment = getAlignment(pos);
            p.Range.InsertParagraphAfter();
            
        }

        private void hojaRespuestas(Document doc)
        {
            insertText("Clave", doc, 1, 13, 1);
            insertText("", doc, 1, 13,1);
            foreach (Examen examen in examenes)
            {
                insertText(examen.Clave, doc,2,12,0);
                insertRespuetas(doc,examen);
            }
            newPage(doc);
            Console.WriteLine("hoja");
        }

        private void header(Document doc)
        {
            insertText("TEC DE MONTERREY Campus Zacatecas", doc, 5, 17, 1);
            insertText("Examen de " + parcial.Materia, doc, 3, 15, 1);
            insertText("Periodo " + parcial.Fecha, doc, 3, 14, 1);
            insertText(parcial.ParcialP + " Parcial", doc, 3, 13, 1);
        }

        private void insertRespuetas(Document doc, Examen examen)
        {
            Table newTable = doc.Tables.Add(doc.Bookmarks.get_Item(ref oEndOfDoc).Range, examen.Problemas.Count, 2, ref oMissing, ref oMissing);
            newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
          //  newTable.AllowAutoFit = true;
            int x = 1;
            foreach (Problema problema in examen.Problemas)
            {
                Cell pro = newTable.Cell(x, 1);
                Cell res = newTable.Cell(x, 2);
                pro.Range.Text = x + ")";
                res.Range.Text = getRespuesta(problema);
                ++x;
            }
        }

        private string getRespuesta(Problema problema)
        {
            int x = 1;
            foreach (Opcion o in problema.Opciones)
            {
                if (o.Respuesta)
                    return getText(x);
                x++;
            }
            return "";
        }



        private void insertText(String text, Document doc,int bold, int size, int pos)
        {
            Paragraph p = doc.Content.Paragraphs.Add(oMissing);
            p.Range.Font.Name = "ARIAL";
            p.Range.Font.Bold = bold;
            p.Range.Font.Size = size;
            p.Range.Text = text;
            p.Range.ParagraphFormat.Alignment = getAlignment(pos);
            p.Range.InsertParagraphAfter();
        }

        private WdParagraphAlignment getAlignment(int pos)
        {
            switch (pos) 
            { 
                case 0:
                    return WdParagraphAlignment.wdAlignParagraphLeft;
                case 1:
                    return WdParagraphAlignment.wdAlignParagraphCenter;
                case 2:
                    return WdParagraphAlignment.wdAlignParagraphRight;
            }
            return WdParagraphAlignment.wdAlignParagraphDistribute;
        }

        private void insertRTF(Document doc,String rtf)
        {
            Paragraph p = doc.Content.Paragraphs.Add(oMissing);
            Clipboard.SetText(rtf, TextDataFormat.Rtf);
            p.Range.Paste();
            p.Range.InsertParagraphAfter();
        }


        private string getText(int x)
        {
            switch (x)
            {
                case 1:
                    return "A)";
                case 2:
                    return "B)";
                case 3:
                    return "C)";
                case 4:
                    return "D)";
            }
            return "";
        }

        private void newPage(Document doc)
        {
            object oPos;
            double dPos = WordApp.InchesToPoints(7);
            doc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter();
            Range wrdRng;
            do
            {
                wrdRng = doc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                wrdRng.ParagraphFormat.SpaceAfter = 6;
                wrdRng.InsertAfter("");
                wrdRng.InsertParagraphAfter();
                oPos = wrdRng.get_Information
                               (Microsoft.Office.Interop.Word.WdInformation.wdVerticalPositionRelativeToPage);
            }
            while (dPos >= Convert.ToDouble(oPos));
            object oCollapseEnd = Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd;
            object oPageBreak = Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak;
            wrdRng.Collapse(ref oCollapseEnd);
            wrdRng.InsertBreak(ref oPageBreak);
            wrdRng.Collapse(ref oCollapseEnd);
            wrdRng.InsertParagraphAfter();
        }
    }
}
